package homework03;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class SetAttrToInstance {
	private Person person = new Person();
	private Class clazz = person.getClass();

	public static void main(String[] args) throws IOException {
		SetAttrToInstance satt = new SetAttrToInstance();
		satt.readInFile();
		System.out.println("------------------------");
		System.out.println(satt.toString());
		System.out.println("------------------------");
	}

	@SuppressWarnings({ "resource" })
	private void readInFile() {
		String path = "C:\\Users\\小苏\\git\\Java_KaiFaJiChu_assignment\\DevelopmentBasic\\src\\homework03\\Person.txt";
		try {
			BufferedReader bufferReader = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
			String text = bufferReader.readLine();
			while (text.length() > 0) {
				analyzeFile(text);
				text = bufferReader.readLine();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			// e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void analyzeFile(String text) {
		String[] values = text.split("=");
		String methodName = "set" + firstCharToUpper(values[0]);
		setAttr(methodName.trim(), values[1].trim());
	}

	private void setAttr(String methodName, Object value) {
		try {
			Method[] method = clazz.getDeclaredMethods();
			for (Method m : method) {
				if (m.getName().equals(methodName)) {
					Class[] paramType = m.getParameterTypes();
					String type = paramType[0].getCanonicalName();
					m.invoke(person, Class.forName(type).getConstructor(String.class).newInstance(value));
					return;
				}
			}
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		}
	}

	@Override
	public String toString() {
		return "idNo:" + person.getIdNo() + "\nname:" + person.getName() + "\nage:" + person.getAge() + "\nsex:"
				+ person.getSex() + "\nisMerried:" + person.getIsMerried();
	}

	private static String firstCharToUpper(String str) {
		char ch[] = str.toCharArray();
		char ch1 = Character.toUpperCase(ch[0]);
		ch[0] = ch1;
		String s = new String(ch);
		return s;
	}
}
